package com.itheima.travel.service.impl;

import com.itheima.travel.constant.RedisConstant;
import com.itheima.travel.mapper.CategoryMapper;
import com.itheima.travel.pojo.Category;
import com.itheima.travel.pojo.CategoryExample;
import com.itheima.travel.req.CategoryVo;
import com.itheima.travel.service.CategoryService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import jodd.time.TimeUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description 分类服务实现
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<CategoryVo> findAllCategory() {

        RBucket<List<CategoryVo>> bucket = redissonClient.getBucket(RedisConstant.CATEGORYSERVICE_FINDALLCATEGORY);
        List<CategoryVo> categoryVoList = bucket.get();
        if(!EmptyUtil.isNullOrEmpty(categoryVoList)) {
            return categoryVoList;
        }
        //查询数据库
        CategoryExample example = new CategoryExample();
        List<Category> categories = categoryMapper.selectByExample(example);
        //更新缓存
        if (!EmptyUtil.isNullOrEmpty(categories)){
            List<CategoryVo> categoryVos = BeanConv.toBeanList(categories, CategoryVo.class);
            bucket.set(categoryVos, 1800, TimeUnit.SECONDS);
        }
        return BeanConv.toBeanList(categories, CategoryVo.class);
    }
}
